const BaseController = require('./base_controller.js');
const DurationPricingService = require('../service/duration_pricing_service.js');

class DurationPricingController extends BaseController {

  /**
   * 添加时长档位
   */
  async addDurationPricing() {
    await this.isAdmin();

    // 数据校验
    let rules = {
      deviceId: 'required|string|name=设备ID',
      duration: 'required|int|min:1|max:1440|name=时长(分钟)',
      price: 'required|int|min:1|name=价格(分)',
      discount: 'float|min:0|max:1|name=折扣',
      description: 'string|max:100|name=档位描述',
    };

    let input = this.validateData(rules);

    try {
      const service = new DurationPricingService();
      const result = await service.addDurationPricing(input);
      
      return this.success(result);
    } catch (error) {
      return this.fail(error.message);
    }
  }

  /**
   * 更新时长档位
   */
  async updateDurationPricing() {
    await this.isAdmin();

    // 数据校验
    let rules = {
      pricingId: 'required|string|name=档位ID',
      duration: 'int|min:1|max:1440|name=时长(分钟)',
      price: 'int|min:1|name=价格(分)',
      discount: 'float|min:0|max:1|name=折扣',
      description: 'string|max:100|name=档位描述',
      status: 'int|in:0,1|name=档位状态',
    };

    let input = this.validateData(rules);

    try {
      const service = new DurationPricingService();
      const result = await service.updateDurationPricing(input.pricingId, input);
      
      return this.success(result);
    } catch (error) {
      return this.fail(error.message);
    }
  }

  /**
   * 删除时长档位
   */
  async deleteDurationPricing() {
    await this.isAdmin();

    // 数据校验
    let rules = {
      pricingId: 'required|string|name=档位ID',
    };

    let input = this.validateData(rules);

    try {
      const service = new DurationPricingService();
      await service.deleteDurationPricing(input.pricingId);
      
      return this.success({ message: '档位删除成功' });
    } catch (error) {
      return this.fail(error.message);
    }
  }

  /**
   * 获取设备档位列表
   */
  async getDevicePricingList() {
    await this.isAdmin();

    // 数据校验
    let rules = {
      deviceId: 'required|string|name=设备ID',
    };

    let input = this.validateData(rules);

    try {
      const service = new DurationPricingService();
      const result = await service.getDevicePricingList(input.deviceId);
      
      return this.success(result);
    } catch (error) {
      return this.fail(error.message);
    }
  }
}

module.exports = DurationPricingController;
